import React, { forwardRef } from 'react';
import { isEqual } from 'lodash';
import TextArea from 'antd/lib/input/TextArea';
import ComboGrid from '@/pages/Transformer/components/ComboGrid';
import styles from './index.less';

function CustomHandlerSelector({ url, value, onChange, params = true, ...rest }) {
  return (
    <>
      <ComboGrid
        url={url}
        className={params ? 'margin-bottom' : ''}
        value={value && value.className ? [value] : []}
        method="get"
        popupStyle={{ width: 600 }}
        placeholder="请选择自定义处理类"
        searchPlaceholder="请输入"
        destroyPopupOnHide
        label="title"
        rowKey="className"
        pick="radio"
        columns={[
          {
            title: '名称',
            dataIndex: 'title',
            ellipsis: true,
          },
          {
            title: '类名',
            dataIndex: 'className',
            ellipsis: true,
          },
          {
            title: 'beanName',
            dataIndex: 'beanName',
            ellipsis: true,
          },
        ]}
        onChange={selectRows => {
          if (selectRows.length > 0) {
            const nextValue = { ...value, ...selectRows[0] };
            if (!isEqual(value, nextValue)) {
              onChange(nextValue);
            }
          } else if (selectRows.length === 0) {
            if (value !== undefined) {
              onChange({
                className: undefined,
                beanName: undefined,
                title: undefined,
                params: undefined,
              });
            }
          }
        }}
        {...rest}
      />
      {params && (
        <TextArea
          className={styles.textarea}
          allowClear
          autoSize={{ minRows: 4 }}
          value={value && value.params}
          onChange={e => {
            const nextValue = { ...value, params: e.target.value };
            if (!isEqual(value, nextValue)) {
              onChange(nextValue);
            }
          }}
          placeholder="自定义参数，在这里填入的字符串会被传到处理器类中"
        />
      )}
    </>
  );
}

export default forwardRef(CustomHandlerSelector);
